package com.itheima.service;

import com.itheima.mapper.PurchaseHistoryMapper;
import com.itheima.pojo.PurchaseHistory;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class PurchaseHistoryService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    public void add(Integer itemId, Integer buyerId, Integer sellerId) {
        //调用PurchaseHistoryMapper.add()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取PurchaseHistoryMapper
        PurchaseHistoryMapper mapper = sqlSession.getMapper(PurchaseHistoryMapper.class);

        //4. 调用方法
        mapper.add(itemId, buyerId, sellerId);

        // 提交事务
        sqlSession.commit();
        // 释放资源
        sqlSession.close();
    }

    public List<PurchaseHistory> selectBySellerId(Integer sellerId) {
        //调用PurchaseHistoryMapper.selectBySellerId()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取PurchaseHistoryMapper
        PurchaseHistoryMapper mapper = sqlSession.getMapper(PurchaseHistoryMapper.class);

        //4. 调用方法
        List<PurchaseHistory> purchaseHistories = mapper.selectBySellerId(sellerId);

        // 释放资源
        sqlSession.close();

        return purchaseHistories;
    }

    public List<PurchaseHistory> selectByBuyerId(Integer buyerId) {
        //调用PurchaseHistoryMapper.selectByBuyerId()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取PurchaseHistoryMapper
        PurchaseHistoryMapper mapper = sqlSession.getMapper(PurchaseHistoryMapper.class);

        //4. 调用方法
        List<PurchaseHistory> purchaseHistories = mapper.selectByBuyerId(buyerId);

        // 释放资源
        sqlSession.close();

        return purchaseHistories;
    }
}
